import { BaseNotify } from '#components'
import { createApp, h } from 'vue'

interface Msg {
  title: string
  content: string | VNode
}

const AppAmount = defineAsyncComponent(() => import('../components/AppAmount.vue'))
let instance: any = null
function initInstance() {
  const div = document.createElement('div')
  document.body.appendChild(div)
  const app = createApp({
    render() {
      return h(BaseNotify, {
        ref: (el: any) => {
          instance = el
        },
      })
    },
  })
  app.mount(div)
}
function useNotify(msg: string | Msg, type: 'error' | 'success' | '') {
  if (!instance) {
    initInstance()
  }
  instance.addMsg(msg, type)
}
function useMoney(value: { type: 'error' | 'success', title: string, label: string, amount: number, showIcon?: boolean, currencyType?: EnumCurrencyKey }) {
  const content = {
    title: value.title,
    content: h('div', { class: 'center' }, [
      h('span', { class: 'mr-1' }, value.label),
      h(AppAmount, { amount: value.amount, showColor: true, showIcon: value.showIcon || false, currencyType: value.currencyType || 'CNY', style: { '--tg-app-currency-icon-size': '1rem', '--tg-app-amount-font-weight': 400, '--tg-app-amount-font-size': '0.75rem' } }),
    ]),
  }
  useNotify(content, value.type)
}

export const message = {
  success(msg: string | Msg) {
    useNotify(msg, 'success')
  },
  error(msg: string | Msg) {
    useNotify(msg, 'error')
  },
  onlyMsg(msg: string | Msg) {
    useNotify(msg, '')
  },
  money(values: { type: 'error' | 'success', title: string, label: string, amount: number, showIcon?: boolean, currencyType?: EnumCurrencyKey }) {
    useMoney(values)
  },
}
